package com.skydonkey.verify;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.JWTVerifier;
import com.skydonkey.dao.AccountMapper;
import com.skydonkey.pojo.po.Account;
import com.skydonkey.pojo.vo.Result;
import com.skydonkey.pojo.vo.ResultEnum;
import com.skydonkey.utils.JWTUtils;
import com.skydonkey.utils.ObjectMapperUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;


@Component
public class AuthorizeInterceptor implements HandlerInterceptor {
    @Resource
    AccountMapper accountMapper;

    String token;

    public String getToken() {
        return token;
    }

    public void setToken(String token) {
        this.token = token;
    }

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object) throws Exception {
        String token = httpServletRequest.getHeader("Authorization");// 从 http 请求头中取出 token
        // 如果不是映射到方法直接通过
        if(!(object instanceof HandlerMethod)){
            return true;
        }
        HandlerMethod handlerMethod=(HandlerMethod)object;
        Method method=handlerMethod.getMethod();
        //检查是否有passtoken注解，有则跳过认证
        if (method.isAnnotationPresent(PassToken.class)) {
            PassToken passToken = method.getAnnotation(PassToken.class);
            if (passToken.required()) {
                return true;
            }
        }
        //检查有没有需要用户权限的注解
        if (method.isAnnotationPresent(VerifyToken.class)) {
            VerifyToken userLoginToken = method.getAnnotation(VerifyToken.class);
            if (userLoginToken.required()) {
                // 执行认证
                if (token == null) {
                    // 在没有登录的情况下发送自定义响应
                    setResponseResult(httpServletResponse, new Result(ResultEnum.RELOGIN));
                    return false;
                }
                // 获取 token 中的 user id
                String id;
                try {
                    id = JWT.decode(token).getAudience().get(0);
                } catch (JWTDecodeException j) {
                    setResponseResult(httpServletResponse, new Result(ResultEnum.RELOGIN));
                    return false;
                }
                Account account = accountMapper.findById(Long.parseLong(id));
                if (account == null) {
                    setResponseResult(httpServletResponse, new Result(ResultEnum.RELOGIN));
                    return false;
                }
                // 验证 token
                JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(account.getPassword())).build();
                try {
                    jwtVerifier.verify(token);
                } catch (JWTVerificationException e) {
                    setResponseResult(httpServletResponse, new Result(ResultEnum.RELOGIN));
                    return false;
                }
                return true;
            }
        }
        return true;
    }


    public static void main(String[] args) {
        Account account = new Account();
        account.setUid(2L);
        account.setPassword("GCvgxc3NUHK7GGTN7k09bg==");
        String token = JWTUtils.generateToken(account);
        //String token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhdWQiOiIyIiwiZXhwIjoxNjk4NTYwMjQ5LCJpYXQiOjE2OTg1NTY2NDl9.yJodNjkKo8Yc4xFM01-vppwWg7idFbVFCRyzlAFSOw4";
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256("GCvgxc3NUHK7GGTN7k09bg==")).build();
        System.out.println(jwtVerifier.verify(token));
    }
    private void setResponseResult(HttpServletResponse httpServletResponse, Result result) throws IOException {
        // 在没有登录的情况下发送自定义响应
        String errorMessage = ObjectMapperUtil.toJSON(result);
        httpServletResponse.setContentType("application/json;charset=UTF-8");
        httpServletResponse.getWriter().write(errorMessage);
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest,
                           HttpServletResponse httpServletResponse,
                           Object o, ModelAndView modelAndView) throws Exception {

    }
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest,
                                HttpServletResponse httpServletResponse,
                                Object o, Exception e) throws Exception {
    }

}
